package com.geoai.featstatusbar.flightcheck.vm

import android.view.View
import com.geoai.basiclib.base.vm.BaseViewModel
import com.zkyt.lib_msdk_ext.ProductManagerExt
import com.zkyt.lib_msdk_ext.component.FlyControllerManagerExt
import com.zkyt.lib_msdk_ext.utils.FlycUtil
import com.zkyt.lib_msdk_ext.utils.RxExt.filterGetOptional
import io.reactivex.Observable
import io.reactivex.rxkotlin.Observables

/**
@author : XPY on 2024/3/7 11:50
@description:
 */
class ItemLastAlterVM(view: View) : BaseViewModel() {

    fun getLatestAlarmObservable(): Observable<LatestAlarm> {
        return Observables.combineLatest(
            ProductManagerExt.getConnectedObservable(),
            FlyControllerManagerExt.getDiagnosticsStateObservable().filterGetOptional()
        ).map { (isConnect, diagnosticsList) ->
            if (!isConnect)
                return@map LatestAlarm(LatestAlarmLevel.NOT_CONNECT)
            else {
                if (diagnosticsList.isEmpty()) {
                    return@map LatestAlarm(LatestAlarmLevel.NORMAL)
                } else {
                    // 取第一个严重警告事件
                    diagnosticsList.forEach { state ->
                        if (state == null) {
                            // 注意这里可能会有null，不要听kotlin "always false"的提示
                            return@forEach
                        }

                        if (FlycUtil.isCriticalAlert(state.alertLevel)) {
                            return@map LatestAlarm(LatestAlarmLevel.CRITICAL, state.message)
                        } else if (FlycUtil.isTakeCareAlert(state.alertLevel)) {
                            return@map LatestAlarm(LatestAlarmLevel.TAKE_CARE, state.message)
                        }
                    }
                    // 没有则返回正常
                    return@map LatestAlarm(LatestAlarmLevel.NORMAL)
                }
            }
        }
    }

    enum class LatestAlarmLevel {
        NORMAL,
        CRITICAL,
        TAKE_CARE,
        NOT_CONNECT,
        UNKNOWN;
    }

    data class LatestAlarm(
        var latestAlarmLevel: LatestAlarmLevel = LatestAlarmLevel.UNKNOWN,
        val alarmContent: String = ""
    )
}



